﻿using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using SharpDX;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Controls;
using System.Windows.Input;
using Telerik.Windows.Controls;
using Telerik.Windows.Documents.Spreadsheet.FormatProviders;
using Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml.Xlsx;
using Telerik.Windows.Documents.Spreadsheet.Model;
using Unity;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class SpecGeneralDataTemplateViewModel : RegionViewModelBase
    {
        private readonly IEventAggregator _eventAggregator;
        private readonly ISpecSheetDataService _InsServ;
        private DelegateCommand<SelectionChangedEventArgs> _templateSelectChangedCommand;
       // private DelegateCommand<EventArgs> _templateDropDownOpenedCommand;
        private ObservableCollection<ComboBoxItemModel<SimpleStringModel>> _specTemplateList;//数据表模板
        private SimpleStringModel _selectedSpecModel;
        private SimpleStringModel _selectedModel;
        private readonly ITemplateSettingService _tempServ;
        private List<Report> _reports;

        public string CmpntID { get; set; }
        private Workbook workbook = new Workbook();
        public Workbook Workbook
        {
            get
            {
                return this.workbook;
            }
            set
            {
                if (this.workbook != value)
                {
                    this.workbook = value;
                    RaisePropertyChanged();
                }
            }
        }
        public ObservableCollection<ComboBoxItemModel<SimpleStringModel>> SpecTemplateList
        {
            get { return _specTemplateList; }
            set { SetProperty(ref _specTemplateList, value); }
        }

        public SimpleStringModel SelectedSpecModel
        {
            get { return _selectedSpecModel; }
            set
            {
                SetProperty(ref _selectedSpecModel, value);
            }
        }
        public SimpleStringModel SelectedModel
        {
            get { return _selectedModel; }
            set { SetProperty(ref _selectedModel, value); }
        }
        public ICommand TemplateSelectChangedCommand
        {
            get
            {
                if (_templateSelectChangedCommand != null) return _templateSelectChangedCommand;
                _templateSelectChangedCommand = new DelegateCommand<SelectionChangedEventArgs>(onTemplateSelectChangedCommand);
                return _templateSelectChangedCommand;
            }
        }
       
        //public bool TestMode { get; set; }

        public ICommand RefreshCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public SpecGeneralDataTemplateViewModel(
            IRegionManager regionManager,
            IDialogService dialog,
            IUnityContainer unityContainer,
            IEventAggregator eventAggregator,
            ISpecSheetDataService achievementService,
            ITemplateSettingService tempServ)
           : base(regionManager, unityContainer, dialog)
        {
            _eventAggregator = eventAggregator;
            _InsServ = achievementService;
            _tempServ = tempServ;
            this.RefreshCommand = new Telerik.Windows.Controls.DelegateCommand(onRefreshCommand);
            this.SaveCommand = new Telerik.Windows.Controls.DelegateCommand(onSaveCommand);

            //dialog.ShowMessage("功能开发中。。。");
            //return;
            // _eventAggregator.GetEvent<CompSelectedEvent>().Subscribe(OnCompSelectedEvent);
        }

        protected override async void OnInitPage(object obj)
        {
          
            base.OnInitPage(obj);
            await Task.Run(() => LoadReports(null));//获取数据表模板


        }
        /// <summary>
        /// 没啥必要
        /// </summary>
        /// <param name="treeNode"></param>
        //private async void OnCompSelectedEvent(ITreeNodeModel treeNode)
        //{
        //    CmpntID = treeNode.Id;
        //    await SpecOut();
        //}

        //控制是否可以多开
        //public override bool IsNavigationTarget(NavigationContext navigationContext)
        //{
        //    return false;
        //}
        //public override async void OnNavigatedTo(NavigationContext navigationContext)
        //{
        //    if (navigationContext.Parameters.ContainsKey(DialogParameterKeys.Title))
        //        Title.TitleText = navigationContext.Parameters[DialogParameterKeys.Title].ToString();
        //    if (navigationContext.Parameters.ContainsKey(DialogParameterKeys.Id))
        //        CmpntID = navigationContext.Parameters[DialogParameterKeys.Id].ToString();
        //    if (navigationContext.Parameters.ContainsKey(DialogParameterKeys.Content))
        //    {
        //        var excelContent = navigationContext.Parameters[DialogParameterKeys.Content] as FileContentResultBaseString;
        //        var bytes = Convert.FromBase64String(excelContent.Data);//server端正好是用的ToBase64String，把byte[]变为的string
        //        var memoryStream = new MemoryStream(bytes);
        //        //return new RESTfulResult<Stream> { data = memoryStream, succeeded = true };

        //        memoryStream.Position = 0;
        //        var length = memoryStream.Length;
        //        var buffer = new byte[length];
        //        memoryStream.Read(buffer, 0, (int)length);
        //        XlsxFormatProvider formatProvider = new XlsxFormatProvider();
        //        Workbook = formatProvider.Import(buffer);
        //    }
        //    else
        //    {
        //        Workbook = new Workbook();
        //    }

        //}
       
        private void onRefreshCommand(object obj)
        { }
        private async void onSaveCommand(object obj)
        {
            try
            {
                XlsxFormatProvider formatProvider = new XlsxFormatProvider();
                if (!string.IsNullOrEmpty(CmpntID))
                {

                    var buffer = formatProvider.Export(workbook);

                    var files = new List<NetworkFileInfo> { new NetworkFileInfo { FileName = "spec.xlsx", Data = buffer } };
                    var blankValueUpdteFlag = true;
                    var RES = await _InsServ.UploadSpecInputAsync(files, GlobalObject.CurrentProject.ProjId.ToString(), GlobalObject.CurrentProject.ProjName.ToString(), CmpntID, blankValueUpdteFlag);
                    if (!RES.succeeded)
                    {
                        switch (RES.statusCode)
                        {
                            case 400:
                            case 500:
                                //业务错误
                                Dialog.ShowAltert(RES.errors);
                                //关闭view
                                break;
                            default:
                                //网络错误
                                Dialog.ShowAltert(RES.errors);
                                LoggerHelper.Current.Error(RES.errors);
                                break;
                        }
                        return;
                    }
                    else
                    {
                        var bytes = Convert.FromBase64String(RES.data.Data);//server端正好是用的ToBase64String，把byte[]变为的string
                        var memoryStream = new MemoryStream(bytes);
                        //return new RESTfulResult<Stream> { data = memoryStream, succeeded = true };

                        memoryStream.Position = 0;
                        var length = memoryStream.Length;
                        var buffer2 = new byte[length];
                        memoryStream.Read(buffer2, 0, (int)length);   
                        Dialog.ShowMessage("保存成功！");
                        formatProvider = new XlsxFormatProvider();
                        Workbook = formatProvider.Import(buffer2);
                        //SpecInputModels.Clear();
                     
                    }
                }

            }
            catch (Exception x)
            {
                string msg = $"保存失败：{x.Message}";
                LoggerHelper.Current.Error(msg, x);
            }
        }

        private async void LoadReports(object obj) //获取数据表模板
        {
            _reports = await _tempServ.GetTemplateLisAsync(GlobalObject.CurrentProject.ProjId.ToString());
            _reports = _reports.Where(x => x.Type == TemplateType.SPEC).ToList();
            var list = new ObservableCollection<ComboBoxItemModel<SimpleStringModel>>();
            _reports.ForEach(x =>
            {
                list.Add(new ComboBoxItemModel<SimpleStringModel>()
                {
                    Name = x.Name,
                    Description = x.Description,
                    IsEnable = true,
                    SelectedModel = new SimpleStringModel { v1 = x.Name }
                });
            });

            SpecTemplateList = list;
            //if (list.Count > 0)
            //{
            //    SelectedSpecModel = list[0].SelectedModel;
            //}
        }
        /// <summary>
        /// 获取数据表通用数据模板信息
        /// </summary>
        /// <param name="obj"></param>
        private async void LoadSpecDataTemplate(string SpecReportName) 
        {
            _reports = await _tempServ.GetTemplateLisAsync(GlobalObject.CurrentProject.ProjId.ToString());
            _reports = _reports.Where(x => x.Type == TemplateType.SPEC).ToList();
            var list = new ObservableCollection<ComboBoxItemModel<SimpleStringModel>>();
            _reports.ForEach(x =>
            {
                list.Add(new ComboBoxItemModel<SimpleStringModel>()
                {
                    Name = x.Name,
                    Description = x.Description,
                    IsEnable = true,
                    SelectedModel = new SimpleStringModel { v1 = x.Name }
                });
            });

            SpecTemplateList = list;
            //if (list.Count > 0)
            //{
            //    SelectedSpecModel = list[0].SelectedModel;
            //}
        }


        private async void onTemplateSelectChangedCommand(SelectionChangedEventArgs obj)
        {
            var eventArgs = obj as SelectionChangedEventArgs;
            if (eventArgs == null) return;
            if (eventArgs.AddedItems.Count < 1) return;


            var report = _reports.FirstOrDefault(x => x.Name == _selectedSpecModel.v1);
            if (report != null && report.Name.IsNotEmptyOrNull())
            {
                try
                {

                    var report2 = report.CloneObject();
                    if (!report2.Name.EndsWith(".xlsx"))
                    {
                        report2.Name += ".xlsx";
                    }
                    var result = await _tempServ.DownloadTemplateFileAsync(GlobalObject.CurrentProject.ProjId.ToString(), report2);
                    string FilePath;
                    Workbook TemplateWorkbook;
                    if (!result.succeeded)
                    {
                        LoggerHelper.Current.Error(result.errors.ToString());

                        Dialog.ShowAltert("模板配置文件不存在，请选中其他模板！！！");
                        FilePath = "";
                        TemplateWorkbook = new Workbook();
                        //excelIsEnable = false;
                        return;
                    }
                    FilePath = AppDomain.CurrentDomain.BaseDirectory.CombinePath("\\Templates\\" + report.Name);
                    using var stream = result.data;
                    var content = await FileHelper.ReadFileContentAsync(stream);
                    FileHelper.WriteFileBinary(FilePath, content);
                    try
                    {
                        var workBook = OpenXlsxFile(FilePath);
                        this.Workbook = workBook;
                        //excelIsEnable = true;
                        return;
                    }
                    catch (Exception x)
                    {
                        Dialog.ShowAltert("打开Excel文件失败，文件可能已加密(损坏)或已被其它进程打开。");
                        FilePath = "";
                        this.Workbook = new Workbook();
                    }
                }
                catch (Exception x)
                {
                    string msg = $"下载模板文件失败：{x.Message}";
                    LoggerHelper.Current.Error(msg, x);
                    Dialog.ShowAltert(msg);
                }
            }
        }

        private Workbook OpenXlsxFile(string file)
        {
            byte[] fileAsByteArray = File.ReadAllBytes(file);
            return OpenXlsxFile(fileAsByteArray);
        }
        private Workbook OpenXlsxFile(byte[] content)
        {
            IBinaryWorkbookFormatProvider formatProvider = new XlsxFormatProvider();
            Workbook workbook = formatProvider.Import(content);
            return workbook;
        }
    }
}
